package com.sanri.tools.modules.redis.service;

import com.alibaba.fastjson.JSON;
import com.sanri.tools.modules.classloader.ClassloaderService;
import com.sanri.tools.modules.core.exception.ToolException;
import com.sanri.tools.modules.redis.dtos.in.SerializerParam;
import com.sanri.tools.modules.redis.service.dtos.DataSetDto;
import com.sanri.tools.modules.redis.service.dtos.RedisConnection;
import com.sanri.tools.modules.redis.service.dtos.RedisType;
import com.sanri.tools.modules.serializer.service.Serializer;
import com.sanri.tools.modules.serializer.service.SerializerChoseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
@Slf4j
public class RedisDataService {

    @Autowired
    private SerializerChoseService serializerChoseService;
    @Autowired
    private ClassloaderService classloaderService;
    @Autowired
    private RedisService redisService;

    /**
     * 设置值
     * @param dataSetDto
     * @throws IOException
     * @throws ClassNotFoundException
     */
    public void keySetValue(DataSetDto dataSetDto) throws IOException, ClassNotFoundException {
        final RedisConnection redisConnection = redisService.redisConnection(dataSetDto.getConnParam());

        SerializerParam serializerParam = dataSetDto.getSerializerParam();

        Serializer keySerializer = serializerChoseService.choseSerializer(serializerParam.getKeySerializer());
        byte[] keyBytes = keySerializer.serialize(dataSetDto.getKey());

        String value = dataSetDto.getValue();
        ClassLoader classloader = classloaderService.getClassloader(dataSetDto.getClassloaderName());
        Class<?> clazz = classloader.loadClass(dataSetDto.getClassName());
        Object parseObject = JSON.parseObject(value, clazz);

        Serializer valueSerializer = serializerChoseService.choseSerializer(serializerParam.getValue());

        switch (RedisType.parse(dataSetDto.getType())){
            case string:
                byte[] valueBytes = valueSerializer.serialize(parseObject);
                redisConnection.set(keyBytes, valueBytes);
                break;
            default:
                throw new ToolException("不支持类型 "+ dataSetDto.getType() + " 的值设置");
        }
    }
}
